# -*- coding: utf-8 -*-

# Define here the models for your spider middleware
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html

from scrapy import signals
import random
import requests
import json
from boss.model import ProxyModel
from twisted.internet.defer import DeferredLock


class BossSpiderMiddleware(object):
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the spider middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_spider_input(self, response, spider):
        # Called for each response that goes through the spider
        # middleware and into the spider.

        # Should return None or raise an exception.
        return None

    def process_spider_output(self, response, result, spider):
        # Called with the results returned from the Spider, after
        # it has processed the response.

        # Must return an iterable of Request, dict or Item objects.
        for i in result:
            yield i

    def process_spider_exception(self, response, exception, spider):
        # Called when a spider or process_spider_input() method
        # (from other spider middleware) raises an exception.

        # Should return either None or an iterable of Request, dict
        # or Item objects.
        pass

    def process_start_requests(self, start_requests, spider):
        # Called with the start requests of the spider, and works
        # similarly to the process_spider_output() method, except
        # that it doesn’t have a response associated.

        # Must return only requests (not items).
        for r in start_requests:
            yield r

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)


class BossDownloaderMiddleware(object):
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the downloader middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_request(self, request, spider):
        # Called for each request that goes through the downloader
        # middleware.

        # Must either:
        # - return None: continue processing this request
        # - or return a Response object
        # - or return a Request object
        # - or raise IgnoreRequest: process_exception() methods of
        #   installed downloader middleware will be called
        return None

    def process_response(self, request, response, spider):
        # Called with the response returned from the downloader.

        # Must either;
        # - return a Response object
        # - return a Request object
        # - or raise IgnoreRequest
        return response

    def process_exception(self, request, exception, spider):
        # Called when a download handler or a process_request()
        # (from other downloader middleware) raises an exception.

        # Must either:
        # - return None: continue processing this exception
        # - return a Response object: stops process_exception() chain
        # - return a Request object: stops process_exception() chain
        pass

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)


# 请求头代理
class UserAgentDownloaderMiddleware(object):
    USER_AGENTS = [
        'Mozilla/5.0(WindowsNT6.2;WOW64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/27.0.1453.94Safari/537.36',
        'Mozilla/5.0(WindowsNT10.0;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/70.0.3538.77Safari/537.36',
        'Mozilla/5.0(WindowsNT6.2;WOW64)AppleWebKit/537.36(KHTMLlikeGecko)Chrome/44.0.2403.155Safari/537.36',
        'Mozilla/5.0(WindowsNT6.1)AppleWebKit/537.36(KHTML,likeGecko)Chrome/41.0.2228.0Safari/537.36',
        'Mozilla/5.0(Macintosh;IntelMacOSX10_11_1)AppleWebKit/537.36(KHTML,likeGecko)Chrome/72.0.3626.121Safari/537.36',
        'Mozilla/5.0(X11;Linuxx86_64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/71.0.3578.98Safari/537.36',
        'Mozilla/5.0(Macintosh;IntelMacOSX10.11;rv:46.0)Gecko/20100101Firefox/46.0',
        'Mozilla/5.0(WindowsNT10.0;WOW64;rv:46.0)Gecko/20100101Firefox/46.0',
        'Mozilla/5.0(Macintosh;IntelMacOSX10_9_3)AppleWebKit/537.75.14(KHTML,likeGecko)Version/7.0.3Safari/7046A194A',
        'Mozilla/5.0(WindowsNT10.0;Win64;x64;rv:72.0)Gecko/20100101Firefox/72.0',
        'Mozilla/5.0(WindowsNT10.0;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/79.0.3945.130Safari/537.36'
    ]

    def process_request(self, request, spider):
        user_agent = random.choice(self.USER_AGENTS)
        request.headers['User-Agent'] = user_agent


# IP代理
class IPProxyDownloaderMiddleware(object):
    # 代理的url
    PROXY_URL = ''
    
    def __init__(self):
        super(IPProxyDownloaderMiddleware, self).__init__()
        self.current_proxy = None
        self.lock = DeferredLock()

    def process_request(self, request, spider):
        # 一开始访问的时候是没有代理的，所以需要添加代理
        if 'proxy' not in request.meta or self.current_proxy.is_expiring:
            self.update_proxy()
        request.meta['proxy'] = self.current_proxy.proxy

    def process_response(self, request, response, spider):
        if response.status != 200 or 'captcha' in response.url:
            # 进入到这里面的ip就是被拉黑了
            # 如果是302或者直接跳转验证码这个代理其实还是存在的，
            # 所以要增加一个判断是否被拉黑的条件
            # 如果没被拉黑那么就设置啦黑
            if not self.current_proxy.blacked:
                self.current_proxy.blacked = True
            self.update_proxy()
            print('%s这个代理被加入黑名单了' % self.current_proxy.ip)
            # 如果来到这里，说明已经被boss直聘识别为爬虫
            # 所以这个请求相当于什么都没有获取到
            # 如果不返回request，那么这个request就相当于没有回去到数据
            # 也就是说这个请求被废掉了，这个数据就没有被抓取到
            # 所以要重新返回request，让这个请求重新加入到调度当中
            # 下次在发送
            return request
        # 如果是正常记得返回response
        # 如果不返回，那么这个response就不会被传道爬虫哪里去
        # 也就得不到解析
        return response

    def update_proxy(self):
        # 枷锁是为了防止请求过快，
        # 加判断视为了防止在当前ip还能用的情况下请求多个ip浪费资源
        self.lock.acquire()
        if not self.current_proxy or self.current_proxy.is_expiring or self.current_proxy.blacked:
            response = requests.get(self.PROXY_URL)
            text = response.text
            print('重新获取到一个代理',text)
            result = json.loads(text)
            # 获取代理成功
            if len(data = result['data']) > 0:
                data = result['data'][0]
                proxy_model = ProxyModel(data)
                self.current_proxy = proxy_model
        self.lock.release()